/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snail.main;

import com.snail.cfg.XLogger;
import com.woniu.utils.code.RunInThread;
import com.woniu.utils.code.RunInThreadHook;
import com.woniu.utils.system.WSystem;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author pm
 */
public class TimeoutManager {

    /**
     * long -1:超时，0:不检查超时,>0,正常检查
     */
    private static final ConcurrentHashMap<Process, Long> exec_list = new ConcurrentHashMap<>();

    public static void addExec(Process p, long timeout) {
        exec_list.put(p, timeout);
    }

    public static long getExecTiemout(Process p) {
        return exec_list.get(p);
    }

    public static long removeExecTiemout(Process p) {
        return exec_list.remove(p);
    }

    public static void start() {
        new RunInThread(new RunInThreadHook() {
            @Override
            public void run() {
                XLogger.logger.trace("TimoutManager started successfull.");
                while (true) {
                    for (Map.Entry<Process, Long> entry : exec_list.entrySet()) {
                        Process process = entry.getKey();
                        Long timeout = entry.getValue();
                        if (timeout > 0 && getTime() - timeout > 0) {
                            exec_list.put(process, -1l);
                            process.destroy();
                        }
                    }
                    WSystem.sleep(100);
                }
            }
        }).start();
    }

    public static long getTime() {
        return new Date().getTime();
    }
}
